<?php

namespace App\Models;

use App\Services\FaceService;
use Illuminate\Database\Eloquent\Model;

/**
 * Class Child
 * @package App\Models
 */
class Child extends Model
{
    const AUTOMATIC_ORDERING = 1;           // 自动订单
    const NOT_AUTOMATIC_ORDERING = 0;       // 手动订单

    protected $table = 'children';

    protected $fillable = [
        'name', 'avatar', 'sex', 'relation', 'morning_rule', 'lunch_rule', 'dinner_rule'
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * @param $value
     */
    public function setAvatarAttribute($value)
    {
        if ($value) {
            $this->attributes['avatar'] = $value;
            $face = new FaceService();
            $face->deletePerson("student-".$this->id);
            $face->createPersonByBinary("student-".$this->id, file_get_contents(public_path($value)));
        }
    }

    /**
     * @return string
     */
    public function getAvatarUrlAttribute()
    {
        return (!empty($this->avatar) && file_exists(public_path($this->avatar))) ? asset($this->attributes['avatar']) : asset('/images/default.png');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function orders()
    {
        return $this->hasMany(BookOrder::class, 'children_id');
    }
}
